﻿using System;
using System.Collections.Generic;

namespace OrderManagement
{
    public class Order : IEquatable<Order>
    {
        public string OrderId { get; set; }
        public string Customer { get; set; }
        public DateTime OrderDate { get; set; }
        public List<OrderDetails> Details { get; set; }

        public double TotalAmount
        {
            get { return Details?.Sum(d => d.Amount) ?? 0; }
        }

        public Order(string orderId, string customer)
        {
            OrderId = orderId;
            Customer = customer;
            OrderDate = DateTime.Now;
            Details = new List<OrderDetails>();
        }

        public void AddDetails(OrderDetails details)
        {
            if (Details.Any(d => d.Equals(details)))
            {
                throw new ArgumentException($"订单明细已存在: {details.ProductName}");
            }
            Details.Add(details);
        }

        public override bool Equals(object obj)
        {
            return Equals(obj as Order);
        }

        public bool Equals(Order other)
        {
            return other != null &&
                   OrderId == other.OrderId;
        }

        public override int GetHashCode()
        {
            return HashCode.Combine(OrderId);
        }

        public override string ToString()
        {
            string detailsInfo = string.Join("\n  ", Details.Select(d => d.ToString()));
            return $"订单号: {OrderId}, 客户: {Customer}, 日期: {OrderDate:yyyy-MM-dd}, 总金额: {TotalAmount:F2}\n明细:\n  {detailsInfo}";
        }
    }
}